from django.contrib.auth.hashers import make_password
from django.shortcuts import render, redirect
# from django.contrib.auth.models import User
from django.contrib.auth import login , logout, authenticate
from django.contrib.auth.models import Permission
from user.models import MyUser
# from user.form import MyUserCreationForm
import random
# Create your views here.

# 使用Django自带的用户验证系统


# # 基于函数（方法）的视图FBV
# def LoginView(request):
#     # 设置标题和另外两个url链接
#     title = '用户登录'
#     unit_2_name ='用户注册'
#     unit_2 = '/user/register'      # 用户注册url，注意此处前面必须有/即/user/register，否则是相对路径user/register
#     unit_1_name = '修改密码'
#     unit_1 = '/user/updatepwd'  # 修改密码url
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         pass_word = request.POST.get('password', '')
#         if User.objects.filter(username=user_name):
#             user = authenticate(username=user_name, password=pass_word)
#             if user:
#                 if user.is_active:
#                     login(request, user)  # 使用了内置的login函数来进行登录验证，两个参数，一个是request对象，第二个是来自authenticate函数返回的对象user
#                 return redirect('/')  # 用户验证通过，页面跳回首页
#         else:
#             tips = '账号密码错误，请重新输入'
#     else:
#         tips = '对不起，该用户不存在，请先注册！'
#     return render(request, 'user.html',context=locals())
#
#
# def LogoutView(request):
#     logout(request)
#     return redirect('/')
#
#
# def RegisterView(request):
#     # 设置标题和另外两个url链接
#     title = '用户注册'
#     unit_2_name = '立即登录'
#     unit_2 = '/user/login'  # 立即登录url
#     unit_1_name = '修改密码'
#     unit_1 = '/user/updatepwd'  # 修改密码url
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         pass_word = request.POST.get('password', '')
#         # 注意，如果登录时不设置密码，那么User.objects.set_unusable_password将会被调用，生成一个随机的密码
#         if User.objects.filter(username=user_name):
#             tips = '对不起，该用户名已经被使用，请重新输入'
#         else:
#             user = User.objects.create_user(username=user_name, password=pass_word)
#             user.save()
#             tips = '恭喜，注册成功，请登录'
#     return render(request, 'user.html', context=locals())
#
#
# def UpdatePwdView(request):
#     # 设置标题和另外两个url链接
#     title = '修改密码'
#     unit_2_name = '立即登录'
#     unit_2 = '/user/login'  # 立即登录url
#     unit_1_name = '立即注册'
#     unit_1 = '/user/register'  #立即注册url
#     new_password = True
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         pass_word = request.POST.get('password', '')
#         new_pass_word = request.POST.get('new_password', '')
#         if User.objects.filter(username=user_name):
#             user = authenticate(username=user_name, password=pass_word)
#             if user:
#                 # 可以使用make_password进行密码加密，该方法可以脱离Auth系统单独使用
#                 # ob_ps = make_password(new_pass_word, None, 'pdkdf2_sha256')
#                 # user.password = ob_ps
#
#                 # check_password是将加密前的密码和加密后的密码进行比对，返回布尔值
#                 user.set_password(new_pass_word)  # 使用内置的密码修改函数，set_password对make_password进行了封装
#                 user.save()
#                 tips = '恭喜，密码修改成功'
#         else:
#             tips = '对不起，该用户不存在'
#     return render(request, 'user.html', context=locals())
#
#
# # 采用邮箱来找回密码，记住该用户的邮箱必须有值，否则不可以
# def FindPwdView(request):
#     title = '找回密码'
#     button = '获取验证码'
#     new_password = False
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         VerificationCode = request.POST.get('VerificationCode', '')
#         user= User.objects.filter(username=user_name)
#         if not user:
#             # 用户不存在
#             tips = '对不起，用户'+user_name+'不存在'
#         else:
#             # 用户存在
#             # 判断验证码是否已经发送
#             if not request.session.get('VerificationCode', ''):
#                 # 发送验证码，并写入session
#                 button = '重置密码'
#                 tips = '验证码已发送'
#                 new_password = True
#                 VerificationCode = str(random.randint(1000, 9999))
#                 request.session['VerificationCode'] = VerificationCode
#                 user[0].email_user('找回密码', VerificationCode)
#                 # 匹配输入的验证码是否正确
#             elif VerificationCode == request.session.get('VerificationCode', ''):
#                 # 对密码进行加密并保存到数据库
#                 dj_ps = make_password(new_password)
#                 user[0].password = dj_ps
#                 user[0].save()
#                 del request.session['VerificationCode']
#                 tips = '恭喜，密码已经重置成功'
#             # 验证码输入错误
#             else:
#                 tips = '验证码错误，请重新获取'
#                 new_password = False
#                 del request.session['VerificationCode']
#     return render(request, 'findpassword.html', context=locals())
#
#
# # 使用表单实现的用户注册，因此首先需要实例化表单，但是我们并不需要从表单中获取数据
# def RegisterFormView(request):
#     if request.method == 'POST':
#         user = MyUserCreationForm(request.POST)
#         if user.is_valid():
#             user.save()
#             tips = '恭喜注册成功！'
#             user = MyUserCreationForm()
#     else:
#         user = MyUserCreationForm()
#     return render(request, 'user_form.html', context=locals())


# 以下代码仅仅为了演示如何设置网页的访问权限，可以全部注释，然后其余功能不受影响
# 这里仅仅只有用户登录，用户注册，和退出登录，其他的请使用上面提供的方法
# 除了这段代码，还有index/views.py中说明的关于用于设置网页的访问权限的index方法

# 用户登录
# def LoginView(request):
#     title = '用户登录'
#     tips = '请先登录'
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         pass_word = request.POST.get('password', '')
#         user = authenticate(username=user_name, password=pass_word)
#         if user:
#             if user.is_active:
#                 # 登录当前用户
#                 login(request, user)
#             return redirect('/')
#         else:
#             tips = '对不起，账号密码错误，请重新输入'
#     else:
#         tips = '对不起，该用户不存在，请先注册'
#     return render(request, 'user_auth_test.html', context=locals())
#
#
# # 用户注册
# def RegisterView(request):
#     title = '用户注册'
#     tips = '欢迎注册'
#     if request.method == 'POST':
#         user_name = request.POST.get('username', '')
#         pass_word = request.POST.get('password', '')
#         if MyUser.objects.filter(username=user_name):  # 注意此处是不能使用authenticate()来验证用户名的
#             tips = '对不起，该用户名已经被使用，请重新输入'
#         else:
#             user = MyUser.objects.create(username=user_name, password=pass_word)
#             user.password = make_password(pass_word)  # 需要对用户密码进行加密
#             user.save()  # 此处依旧需要save方法
#
#             # 添加权限(默认情况下，新用户是没有任何权限的)
#             permission = Permission.objects.filter(codename='Visit_Product')[0]
#             user.user_permissions.add(permission)  # 给用户新增这个权限（必须在user_permissions这个属性上面）
#
#             tips = '恭喜，注册成功，请登录'
#             return redirect('/user/login')
#     return render(request, 'user_auth_test.html', context=locals())
#
#
# # 退出登录
# def LogoutView(request):
#     logout(request)
#     return redirect('/')



# 以下代码仅仅为了演示如何使用验证码，可以全部注释，然后其余功能不受影响
# 这里仅仅只有用户登录功能其他的请使用上面提供的方法
# 除了这段代码，还有user/views.py, MyDjango/urls.py, user/urls.py,user.html
# from user.form import CaptchaLoginTestForm
#
#
# # 用户登录
# def LoginView(request):
#     if request.method == 'POST':
#         form = CaptchaLoginTestForm(request.POST)
#         # 验证表单数据
#         if form.is_valid():
#             user_name = form.cleaned_data['username']
#             pass_word = form.cleaned_data['password']
#             if MyUser.objects.filter(username=user_name):
#                 user = authenticate(username = user_name, password=pass_word)
#                 if user:
#                     if user.is_active:
#                         login(request, user)
#                         tips = '登录成功！'
#                 else:
#                     tips = '账号密码错误，请重新输入！'
#             else:
#                 tips = '对不起，该用户不存在，请注册！'
#     elif request.method == "GET":
#         form = CaptchaLoginTestForm()
#     return render(request, 'user_captcha.html', locals())
#
#
# # ajax接口实现动态验证码验证
# from django.http import JsonResponse
# from captcha.models import CaptchaStore
#
#
# def AjaxVal(request):
#     if request.is_ajax():
#         # 用户输入的验证码结果
#         response = request.GET(['response'])
#         # 隐藏域的value值
#         hashkey = request.GET(['hashkey'])
#         cs = CaptchaStore.objects.filter(response=response, hashkey=hashkey)
#         # 若存在cs则验证成功，否则就验证失败
#         if cs:
#             json_data = {'status': 1}
#         else:
#             json_data = {'status': 0}
#         return JsonResponse(json_data)
#     else:
#         json_data = {'status': 0}
#         return JsonResponse(json_data)



# 以下代码仅仅为了演示如何使用第三方登录，可以全部注释，然后其余功能不受影响
# 这里仅仅只有用户注册功能，其他的请使用上面提供的方法
from django.http.response import HttpResponse


# 用户注册界面
def LoginView(request):
    title = '用户注册'
    return render(request, 'user_auth2_django_test.html', locals())


# 注册后回调的页面
def success(request):
    return HttpResponse('恭喜注册成功！')
